import React, { Component } from 'react';
import QueueAnim from 'rc-queue-anim';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import { List, Button, DatePicker, Icon, Tools } from 'weaver-mobile';
import { Form, Upload } from 'weaver-mobile-page';
import { FormatDate } from '../util';

const getLabel = Tools.getLabel;

const frontItem = ['groupvotename', 'themepic'];
const backItem = ['checkmode', 'maxvoteoption', 'voteendtime', 'voteremind', 'votesec'];

@withRouter
@inject('newStore', 'listStore')
@observer
class NewVote extends Component {
  constructor(props) {
    super(props)
    this.prefixCls = 'group-vote-new'
  }
  
  componentDidMount() {
    const { newStore: { initiateVote } } = this.props;
    initiateVote();
  }

  shouldComponentUpdate(nextProps) {
    if (nextProps.history.action === 'POP' && nextProps.location.pathname === '/groupVote/new') {
      this.props.history.go(-1);
      return false;
    }
    return true
  }

  componentWillUnmount() {
    this.onCancel();
  }
  
  getFrontFields = (form) => {
    const { newStore: { themeUpload, setStoreState, themeImages } } = this.props;
    const { conditioninfo, isInit } = form;
    const { checkmode } = form.formParams;
    const fields = [];
    if (isInit) {
      conditioninfo.forEach((group) => {
        group.items.forEach((field) => {
          if (frontItem.indexOf(field.domkey[0]) > -1) {
            if (field.domkey[0] === 'themepic') {
              let themParams = toJS(themeImages).length > 0 ? { showUpload: false } : {};
              fields.push(
                <div className={`${this.prefixCls}-form-themepic`}>
                  <div className="am-list-label">{getLabel('513876','主题图片') }</div>
                  <div className='am-list-content '>
                    <Upload
                      inForm
                      store={themeUpload}
                      datas={toJS(themeImages)}
                      uploadUrl="/api/groupchatvote/upload/uploadImgForGroupLoad"
                      listType="img"
                      limitType="jpg,jpeg,png"
                      maxFilesNumber={1}
                      rowKey='id'
                      onChange={(ids, datas) => {
                        // let id = ids.indexOf(',') && ids.split(',')[0] || ids;
                        setStoreState({themeImages: datas}); 
                        form.updateField('themepic', ids)
                      }}
                      {...themParams}
                    />
                  </div>
                </div>
              )
            } else {
              fields.push(<Form.Item
                key={field.domkey.join('__')}
                form={form}
                fieldConfig={field}
                onChange={(field, val) => {
                  form.onChange(field, val);
                  if (field.domkey[0] === 'checkmode' && val === '0') {
                    form.updateField('maxvoteoption', '')
                  }
                }}
                fieldWillRender={(field, formParams) => {
                  if (field.domkey[0] === 'maxvoteoption' && formParams.checkmode === '0') {
                    return false;
                  }
                }}
                extra={field.domkey[0] === 'checkmode' && checkmode === '1' ? <div className='groupvote-tip'>{getLabel('516173','输入0表示不限制')}</div> : null}
              />)
            }
          }
        })
      })
    }
    return fields;
  }

  getBackFields = (form) => {
    const { conditioninfo, isInit } = form;
    const { voteendtime, checkmode } = form.formParams;
    const fields = [];
    if (isInit) {
      conditioninfo.forEach((group) => {
        group.items.forEach((field) => {
          if (backItem.indexOf(field.domkey[0]) > -1) {
            if (field.domkey[0] === 'voteendtime') {
              fields.push(
                <DatePicker
                  key={field.domkey.join('__')}
                  value={voteendtime}
                  minDate={new Date()}
                  onOk={val => {
                    let chooseTime = FormatDate(val, 'yyyy-MM-dd HH:mm:ss')
                    form.updateField('voteendtime', chooseTime);
                  }}
                  onClear={() => form.updateField('voteendtime', '')}
                >
                  <List.Item arrow="horizontal"><span style={{paddingLeft: 7, color: '#333'}}>{field.label}</span></List.Item>
                </DatePicker>
              )
            } else {
              fields.push(<Form.Item
                key={field.domkey.join('__')}
                form={form}
                fieldConfig={field}
                onChange={(field, val) => {
                  form.onChange(field, val);
                  if (field.domkey[0] === 'checkmode' && val === '0') {
                    form.updateField('maxvoteoption', '')
                  }
                }}
                fieldWillRender={(field, formParams) => {
                  if (field.domkey[0] === 'maxvoteoption' && formParams.checkmode === '0') {
                    return false;
                  }
                }}
                extra={field.domkey[0] === 'votesec' ? <div className='groupvote-tip'>{getLabel('522885','开启后，只有发布者才可查看投票人统计')}</div> : field.domkey[0] === 'checkmode' && checkmode === '1' ? <div className='groupvote-tip'>{getLabel('516173','输入0表示不限制')}</div> : null}
              />)
            }
          }
        })
      })
    }
    return fields;
  }

  /* 投票选项 */
  renderVoteOpts = (key) => {
    const { newStore: { voteOptions, optionFormsMap, deleteOption } } = this.props;
    return (
      <div className={`${this.prefixCls}-form-options`} key={key}>
        <div className={`${this.prefixCls}-form-options-title`}>
          {getLabel('516196','可上传一张与投票主题相关的图片')}
        </div>
        <div className={`${this.prefixCls}-form-options-container`}>
          {
            toJS(voteOptions) && Object.keys(toJS(voteOptions)).map(key => {
              if (optionFormsMap[key]) {
                return (
                  <Form store={optionFormsMap[key]} key={key}>
                    <List>
                      <QueueAnim style={{overflowX: 'hidden'}} className={`${this.prefixCls}-form-options-container-item`}>
                        {key > 2 && <Icon type="shanchu" onClick={() => deleteOption(key)}/>}
                        <div>
                          {this.renderOptionItem(optionFormsMap[key], toJS(voteOptions)[key])}
                        </div>
                      </QueueAnim>
                    </List>
                  </Form>
                )
              } else return null;
            })
          }
        </div>
        <div className={`${this.prefixCls}-form-options-addOps`} onClick={() => this.addOption(voteOptions)}>
          <Icon type="tianjia"/>{getLabel('502268','添加选项')}
        </div>
      </div>
    )
  }

  renderOptionItem = (form, data) => {
    const { conditioninfo, isInit } = form;
    const fields = [];
    if (isInit) {
      conditioninfo.forEach(group => {
        group.items.forEach((field) => {
          const fieldProps = field.domkey[0] === 'optionContent' ? {...field, otherParams: {
            placeholder: `${getLabel('386817','选项')}${data.key}`
          }} : field;
          fields.push(<Form.Item
            key={`${field.domkey[0]}_ops_${data.id}`}
            className={`ops_${field.domkey[0]}`}
            form={form}
            fieldConfig={fieldProps}
            onChange={(...arg) => {
              form.onChange(...arg);
            }}
          />)
        })
      })
    }
    return fields;
  }

  /* 添加选项 */
  addOption = (data) => {
    const { newStore: { changeOption, setStoreState } } = this.props;
    const optArr = Object.keys(toJS(data));
    const objectKey = Number(optArr[optArr.length-1]) + 1;
    setStoreState({voteOptions: {...data, [objectKey]: {key: objectKey}}}, changeOption);
  }

  // 发布回调
  publishCallBack = ({groupChatAdd: { votingid, votetheme, enddate, endtime, themeimagesrc }}) => {
    const { history, listStore: { getGroupVoteList, groupid, votingNewLayout } } = this.props;
    if (window.em) {
      let checkApi = window.em.checkJsApi("sendMsg");
      if (checkApi) {
        window.em.sendMsg({
          targetId: groupid, // 消息会话ID
          msgType: 10, // 消息类型：1-文本 2-链接 10-E6分享消息
          msgInfo: {
            content: votetheme, // 分享标题（必填）
            desc: `${getLabel('18111','截止时间：')} ${enddate} ${endtime}`, // 分享描述（非必填）
            canforward: 0, // 消息是否允许转发 1：是（默认） 0：否
            sharetypename: getLabel('514291','群投票'), //消息类型显示标题，没有则按sharetype显示
            sharetypeicon: '', //消息类型显示图标
            sharetypebgcolor: '#9999FF', //消息类型背景颜色，没有则按sharetype显示
            showimage: themeimagesrc, //消息显示图片地址，没有则不显示图片
            linkurl: `/spa/groupVote/static4mobile/index.html#/voting/${votingid}`, // 消息链接地址（必填）
            linkurl_pc: `/spa/smallApp/static/index.html#/main/groupVoting/groupVotingList?id=${votingid}`, //PC端消息链接地址，如果没有则取linkurl值
            sharetype: 'voting', // 分享数据类型,值有"doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
            shareid: votingid, // 分享的数据ID（必填）
            opentype: 1, //移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
            opentype_pc: 1,//PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
          },
          success: (res) => {
            // console.log('success',res)
          },
          fail: (res) => {
            // console.log('fail',res)
          },
        })
      }
    }
    getGroupVoteList();
    history.push(`${votingNewLayout.path}/${votingid}`);
    this.onCancel();
  }

  onCancel = () => {
    const { newStore: { clear, newVoteForm } } = this.props;
    clear();
    newVoteForm.resetFields();
  }

  render () {
    const { listStore: { groupid, isgroup }, newStore: { newVoteForm, publishVote, publishLoading } } = this.props;
    return (
      <div className={this.prefixCls}>
        <div className={`${this.prefixCls}-form`}>
          <Form store={newVoteForm}>
            <List>
              <QueueAnim style={{overflowX: 'hidden'}}>{this.getFrontFields(newVoteForm)}</QueueAnim>
            </List>
          </Form>
          { this.renderVoteOpts() }
          <Form store={newVoteForm}>
            <List>
              <QueueAnim style={{overflowX: 'hidden'}}>{this.getBackFields(newVoteForm)}</QueueAnim>
            </List>
          </Form>
        </div>
        <Button
          type='primary' 
          loading={publishLoading} 
          disabled={publishLoading}
          onClick={() => publishVote({ groupid, isgroup }, this.publishCallBack)}
        >
          { publishLoading ? getLabel('513695','发布中') : getLabel('114','发布') }
        </Button>
      </div>
    )
  }
}

export default NewVote